package com.hr.demo.service.impl;

import com.hr.demo.config.State;
import com.hr.demo.entity.ResponseJson;
import com.hr.demo.entity.User;
import com.hr.demo.exception.BusinessException;
import com.hr.demo.mapper.UserMapper;
import com.hr.demo.service.UserService;
import com.hr.demo.session.HttpSession;
import com.hr.demo.utils.MD5Util;
import com.hr.demo.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpSession httpSession;
    @Autowired
    private ThreadLocal<User> threadLocal;

    @Override
    public ResponseJson login(String account, String pwd) {
        User user = userMapper.selectUserByAccount(account);
        if (user != null) {
            pwd = MD5Util.md5(pwd);
            if (user.getPwd().equals(pwd)) {
                String token = TokenUtil.token();
                httpSession.set(token, user);
                return new ResponseJson(State.SUCCESS, "登录成功", token);
            }
        }
        return new ResponseJson(State.FAIL, "账户密码不正确");
    }

    @Override
    public ResponseJson geuMyInfo() {
        User user = threadLocal.get();
        user = userMapper.selectUserByAccount(user.getAccount());
        return new ResponseJson(State.SUCCESS, "查询成功", user);
    }

    @Override
    public ResponseJson add(User user) {
        User user1 = userMapper.selectUserByAccount(user.getAccount());
        if (user1 == null) {
            user.setPwd(MD5Util.md5(user.getPwd()));
            int x = userMapper.insertUser(user);
            if ( x==1) {
                return new ResponseJson(State.SUCCESS, "账户创建成功");
            }else {
                return new ResponseJson(State.FAIL,"账户创建失败");
            }
        } else {
            return new ResponseJson(State.FAIL, "此账号已存在");
        }
    }

//    @Override
//    public ResponseJson setHeadPortrait(String filePath) {
//    }
}
